import re
from Chapter import Chapter
from servicios.UrlHelper import UrlHelper
from LiLoader import LiLoader

class Season(LiLoader):

    def get_chapter(self, nChapter):
        if (self._chapters is None):
            self.load_chapters()
            
        nChapter = str(nChapter)
        if (self.get_chapters().has_key(nChapter)):
            return self.get_chapters()[nChapter]
        
        return None

    def get_chapters(self):
        if (self._chapters is None):
            self.load_chapters()

        return self._chapters
    
    def load_chapters(self):
        html = UrlHelper.get_chapters(self._id)
        self._chapters = {}
        self.load_li(html)

    def load_especific_data(self, item):
        matches = re.findall('"(\d+)".*<span.*>(\d+)</span> (.*)</li>', str(item))
        matches = matches.pop(0)
        self._chapters[str(matches[1])] = Chapter(self,matches[0], matches[1], matches[2])


    _chapters = None
    _serie = None
    _id = 0
    _number = 0
    _total_chapters = None
    def __init__(self, serie, idSeason, seasonNumber):
        self._id = int(idSeason)
        self._serie = serie
        self._number = int(seasonNumber)

    def __str__(self):
        return 'Season ' + self._number + ' id ' + self._id

    def get_serie(self):
        return self._serie

    def get_id(self):
        return self._id

    def get_number(self):
        return self._number

    def get_total_chapters(self):
		if (self._total_chapters is None):
			self.load_data()
		return self._total_chapters

    def load_data(self):
        html = UrlHelper.get_season_data(self._id)

        match = re.findall('<b>Episodios:</b>[ ]*(\d+)', html)
        self._total_chapters = int(match[0])